//
//  WHProUserModel.m
//  BigVPN
//
//  Created by wanghe on 2017/5/8.
//  Copyright © 2017年 wanghe. All rights reserved.
//

#import "WHProUserModel.h"

static NSString* kUsernameDefaultsKey = @"vpn_username_key";
static NSString* kPasswordDefaultsKey = @"vpn_password_key";
static NSString* kExpireddateDefaultsKey = @"vpn_expired_key";
static NSString* kServeraddrDefaultsKey = @"vpn_serveraddr_key";
static NSString* kUserIsValidDefaultsKey = @"vpn_isvalid_key";


@implementation WHProUserModel
- (instancetype) init{
    if(self = [super init])
    {
        _username = @"";
        _password = @"";
        _serverAddress = @"";
        _expiredDate = @"";
    }
    return self;
}

//- (void) setExpiredDate:(NSString *)expiredDate
//{
//    _expiredDate = [expiredDate copy];
//    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//    NSDate* expired = [formatter dateFromString:_expiredDate];
//    NSDate* now = [NSDate new];
//    if([expired earlierDate:now] != expired)
//    {
//        self.isValid = YES;
//    }
//}

- (BOOL) alreadyExpired
{
    if(!_expiredDate || _expiredDate.length==0) return YES;
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate* expired = [formatter dateFromString:_expiredDate];
    NSDate* now = [NSDate new];
    if([expired earlierDate:now] != expired)
    {
        return NO;
    }
    return YES;
}


- (BOOL) saveToUserDefaults
{
    NSAssert(self.username.length!=0, @"vpn username can't be empty!");
    NSAssert(self.password.length!=0, @"vpn password can't be empty!");
    NSAssert(self.serverAddress.length!=0, @"vpn server address can't be empty!");
    NSAssert(self.expiredDate.length!=0, @"vpn expired date can't be empty!");
    
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setValue:self.username forKey:kUsernameDefaultsKey];
    [userDefaults setValue:self.password forKey:kPasswordDefaultsKey];
    [userDefaults setValue:self.serverAddress forKey:kServeraddrDefaultsKey];
    [userDefaults setValue:self.expiredDate forKey:kExpireddateDefaultsKey];
    
    return [userDefaults synchronize];
}


+ (WHProUserModel*) loadFromUserDefaults
{
    WHProUserModel* model = [WHProUserModel new];
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    model.username = [userDefaults valueForKey:kUsernameDefaultsKey];
    model.password = [userDefaults valueForKey:kPasswordDefaultsKey];
    model.expiredDate = [userDefaults valueForKey:kExpireddateDefaultsKey];
    model.serverAddress = [userDefaults valueForKey:kServeraddrDefaultsKey];
    
    if(model.username.length!=0 && model.password.length!=0 && model.expiredDate.length!=0 && model.serverAddress.length!=0)
    {
        return model;
    }else{
        return nil;
    }
}

@end
